#-*- conding: encoding -*-
#!/usr/bin/python3
'''
Author: ruanchao
Date: 2021-11-18 14:57:26
LastEditTime: 2021-11-19 14:35:52
LastEditors: Please set LastEditors
Description: mysql连接方法配置
FilePath: \stock-analysis-python\mysqlHelper.py
'''
import pymysql

config = {
    "host": '127.0.0.1',
    "port": 3306,
    "user": 'root',
    "password": 'ruanchao1993!',
    "db": 'stock',
    "charset": 'utf8'
}


class mysqlHelper:
    def __init__(self):
        self.host = config["host"]
        self.port = config["port"]
        self.user = config["user"]
        self.password = config["password"]
        self.db = config["db"]
        self.charset = config["charset"]
        self.con = None
        self.cursor = None

    def create_con(self):
        """
        创建连接
        """
        try:
            self.con = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password,
                                       database=self.db, charset='utf8')
            self.cursor = self.con.cursor(pymysql.cursors.DictCursor)  # 游标对象
            return True
        except Exception as e:
            print(e)
            return False

    #
    def close_con(self):
        """
        关闭链接
        """
        if self.cursor:
            self.cursor.close()
        if self.con:
            self.con.close()

    # sql执行
    def execute_sql(self, sql):
        """
        执行插入/更新/删除语句
        """
        try:
            self.create_con()
            print("execute:", sql)
            self.cursor.execute(sql)
            self.con.commit()
        except Exception as e:
            print(e)
        finally:
            self.close_con()

    def select(self, sql, *args):
        """
        执行查询语句
        """
        try:
            self.create_con()
            print("select sql:", sql)
            self.cursor.execute(sql, args)
            res = self.cursor.fetchall()
            return res
        except Exception as e:
            print(e)
            return False
        finally:
            self.close_con()

